package client

import (
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core/request"
	"likeadmin/core/response"
	"likeadmin/model/client"
)

type IReadRecordsService interface {
	List(page request.PageReq, listReq req.ReadRecordsListReq) (res response.PageResp, e error)
}

// NewReadRecordsService 初始化
func NewReadRecordsService(db *gorm.DB) IReadRecordsService {
	return &readRecordsService{db: db}
}

// readRecordsService 阅读记录服务实现类
type readRecordsService struct {
	db *gorm.DB
}

// List 阅读记录列表
func (srv readRecordsService) List(page request.PageReq, listReq req.ReadRecordsListReq) (res response.PageResp, e error) {
	// 分页信息
	limit := page.PageSize
	offset := page.PageSize * (page.PageNo - 1)
	// 查询
	model := srv.db.Model(&client.ReadRecords{})
	if listReq.Uid > 0 {
		model = model.Where("uid = ?", listReq.Uid)
	}
	if listReq.SeriesId != "" {
		model = model.Where("series_id = ?", listReq.SeriesId)
	}
	if listReq.DramaId != "" {
		model = model.Where("drama_id = ?", listReq.DramaId)
	}
	if !listReq.StartStartTime.IsZero() {
		model = model.Where("start_time >= ?", listReq.StartStartTime.Unix())
	}
	if !listReq.StartEndTime.IsZero() {
		model = model.Where("start_time <= ?", listReq.StartEndTime.Unix()+(3600*24-1))
	}
	if !listReq.LastStartTime.IsZero() {
		model = model.Where("last_time >= ?", listReq.LastStartTime.Unix())
	}
	if !listReq.LastEndTime.IsZero() {
		model = model.Where("last_time <= ?", listReq.LastEndTime.Unix()+(3600*24-1))
	}

	// 总数
	var count int64
	err := model.Count(&count).Error
	if e = response.CheckErr(err, "List Count err"); e != nil {
		return
	}
	// 数据
	var objs []client.ReadRecords
	err = model.Limit(limit).Offset(offset).Order("id desc").Find(&objs).Error
	if e = response.CheckErr(err, "List Find err"); e != nil {
		return
	}

	// 收集所有剧集ID
	dramaIds := make([]string, len(objs))
	for i, record := range objs {
		dramaIds[i] = record.DramaId
	}

	// 批量查询剧集信息
	var dramas []client.Drama
	if len(dramaIds) > 0 {
		err = srv.db.Model(&client.Drama{}).Where("drama_id IN ?", dramaIds).Find(&dramas).Error
		if e = response.CheckErrDBNotRecord(err, "Drama Find err"); e != nil {
			return
		}
	}

	// 创建剧集ID到剧集信息的映射
	dramaMap := make(map[string]client.Drama)
	for _, drama := range dramas {
		dramaMap[drama.DramaId] = drama
	}

	resps := []resp.ReadRecordsListReq{}
	response.Copy(&resps, objs)

	for i, recordsListReq := range resps {
		drama, exists := dramaMap[recordsListReq.DramaId]
		if !exists {
			continue
		}
		resps[i].DramaTitle = drama.Title
	}
	return response.PageResp{
		PageNo:   page.PageNo,
		PageSize: page.PageSize,
		Count:    count,
		Lists:    resps,
	}, nil
}
